from gTixi import *
from gTixi import wadapter as wad
'''
import sys
starMessager.output(sys.version)
'''
from m5stack import *
from m5stack_ui import *
from uiflow import *
import wifiCfg
import time



class offStatus(baseMod):
    def __init__(self,mi):
        super(offStatus,self).__init__(mi)
        

    def show(self):
        self.output(" ")



class sysInfo(baseMod):
    def __init__(self,mi):
        super(sysInfo,self).__init__(mi)
        self.pointer = 1
        env = wad.strWaEnv
        self.lines = []
        i=0
        splitLen = 17
        if self.dev == 'zkb':
            splitLen = 15
        while env[i*splitLen:]:
            self.lines.append(env[i*splitLen:i*splitLen+splitLen])
            i += 1
        self.length = len(self.lines)
    def movePointer(self,shift):
        self.pointer = (self.pointer-1 + shift) % (self.length-2)+1
    def show(self):
        menuItem = self.lines
        output = ''
        if len(menuItem)<3:
            for _ in range(3-len(menuItem)):
                menuItem.append('')
        if self.pointer == 0:
            displayList = [0,1,2]
        elif self.pointer == len(menuItem)-1:
            displayList = [len(menuItem)-3,len(menuItem)-2,len(menuItem)-1]
        else:
            displayList = [self.pointer-1,self.pointer,self.pointer+1]
        for (i,item) in enumerate(menuItem):
            if i in displayList:
                output += item + '\n'
        if self.dev == 'zkb':
            output += " A    ←    ↓    ↑    →    B"
        else:
            output = '系统信息\n' + output
        self.output(output)
    def InputKey(self,key):
        if not key:
            return
        if key in "UuH":
            self.movePointer(-1)
            self.show()
        elif key in "DdTAP":
            self.movePointer(1)
            self.show()
        elif key in "LBN":
            self.backToMenu()

class fitTime(baseMod):
    def __init__(self,mi):
        super(fitTime,self).__init__(mi)
        self.conn()
        
    def conn(self):
        wifiCfg.doConnect('fccwifi', 'FCCOFFICEWIFI')
        self.output("标准化时间：\n"+"联网成功\n"
            +"获取时间中..."
            +"\n↑ 获取 ↓ 连网")  
    def show(self):
        if wifiCfg.wlan_sta.isconnected():
            rtc.settime('ntp', host='cn.pool.ntp.org', tzone=8)
            
            self.output(
                "标准化时间：\n"+"获取时间成功\n"
                +rtc.printRTCtime()
                +"\n↑ 获取 ↓ 连网")
        else:
            self.output("标准化时间：\n"+"无网络连接\n"
            +"请重新联网"
            +"\n↑ 获取 ↓ 连网")

    def InputKey(self,key):
        if not key:
            return
        if key in "UHB":
            self.show()
        elif key in "D":
            self.conn()
        elif key in "LN":
            self.backToMenu()

class timer(baseMod):
    def __init__(self,mi):
        super(timer,self).__init__(mi)
        self.loadlog()
        
        if self.log['isStart']:
            self.starts = self.log['startTime']
            self.end = 'working...'
        else:
            self.starts = 'No Task'
            self.end = 'waiting...'
        self.show()
    def show(self):
        self.output(
            "欢迎来到计时器\n"
            +self.starts+'\n'
            +self.end+'\n'
            +"↑ 开始 ↓ 结束")
        self.savelog()
    def loadlog(self):
        d = rtc.datetime()
        dateFile = "logTimer" + str(d[0]) + str(d[1]) + '.txt'
        try:
            with open(dateFile,"r") as f:
                self.log = eval(f.read())
        except:
            self.log = {
                "isStart": False,
                "startTime":"",
                "sTime":None,
                "logs": []
            }
    def savelog(self):
        d = rtc.datetime()
        dateFile = "logTimer" + str(d[0]) + str(d[1]) + '.txt'
        with open(dateFile,"w") as f:
            f.write(str(self.log))
    def startTimer(self):
        self.log["startTime"] = str(rtc.printRTCtime())
        self.log["sTime"] = rtc.datetime()
        self.log["isStart"] = True
        self.starts = self.log["startTime"]
        self.end = "working..."
        self.show()
    def endTimer(self):
        if not self.log["isStart"]:
            self.startTimer()
            return
        def duringTime(time1,time2):
            totalDif = 0
            min = [60.0,1.0,1.0/60]
            for i in range(3):
                totalDif += (time2[i+4]-time1[i+4])*min[i]
                print(totalDif)
            return "{:.4g}min".format(totalDif)
        self.log["isStart"] = False
        self.end = duringTime(self.log["sTime"],rtc.datetime())
        self.starts = str(rtc.printRTCtime())
        self.log["logs"].append({
            "start": self.log["startTime"],
            "end": self.starts,
            "during":self.end
        })
        self.log["startTime"] = ""
        self.log["sTime"] = None
        self.show()

    def InputKey(self,key):
        if not key:
            return
        if key in "UuH":
            self.startTimer()
        elif key in "DdTAPRB":
            self.endTimer()
        elif key in "LN":
            self.backToMenu()   

class timerLog(baseMod):
    def __init__(self,mi):
        super(timerLog,self).__init__(mi)
        
        d = rtc.datetime()
        self.displayDate = "{:4d}{:2d}".format(d[0],d[1])
        dateFile = "logTimer" + str(d[0]) + str(d[1]) + '.txt'
        
        try:
            with open(dateFile,"r") as f:
                self.log = eval(f.read())
                self.maxLength = len(self.log['logs'])
                self.log['logs'].reverse()
            self.islog = True
        except:
            self.islog = False
            self.maxLength = 1
        self.selectLog = 0
        
        
    def show(self):
        if self.islog == False:
            self.output("No Logs")
            return
        
        tlog = self.log['logs'][self.selectLog]
        
        logSeq = "({}/{})".format(self.selectLog+1, self.maxLength)
        
        self.output(
            self.displayDate + logSeq + '\n'
            + tlog["start"]+'\n'
            + tlog["end"] + '\n'
            + tlog["during"]
        )
        

    def InputKey(self,key):
        if not key:
            return
        if key in "U":
            self.selectLog = (self.selectLog-1) % self.maxLength
            self.show()
        elif key in "DB":
            self.selectLog = (self.selectLog+1) % self.maxLength
            self.show()
        elif key in "L":
            self.backToMenu()         

class btrTest(baseMod):
    def __init__(self,mi):
        super(btrTest,self).__init__(mi)
    def show(self):
        self.output(
            "待机时间测试\n"
            +'一旦开始无法停止\n'
            +'\n'
            +"↑ 开始测试")        
    def testStart(self):
        logs = {
            "start":str(rtc.printRTCtime()),
            "end":"",
            "log":[]
            }
        self.output(
            "待机时间测试中\n"
            +logs["start"]+'\n'
            +logs["end"]+'\n'
            +"0min")
        
        tag = 1
        timec = 0
        while True:
            if tag == 1:
                tag = 0
            else:
                tag = 1
            t = str(rtc.printRTCtime())
            logs["end"] = t
            logs["time"] = timec
            logs["log"].append([t,str(power.getBatVoltage())])
            with open("btrTest"+str(tag)+".txt","w") as f:
                f.write(str(logs))
            self.output(
                "待机时间测试中\n"
                +logs["start"]+'\n'
                +logs["end"]+'\n'
                +str(timec)+"min")
            timec = timec + 1
            wait(60)
    def InputKey(self,key):
        if not key:
            return
        if key in "UuH":
            self.testStart()
        elif key in "LN":
            self.backToMenu()  
            

devMenu = {
    "1.计时器":{
        "1.工作计时":timer,
        "2.计时日志":timerLog,
        "3.待机测试":btrTest,
        "4.时间校准":fitTime,
        "5.返回":0
    },
    "2.系统信息":{
        "1.基本信息":sysInfo,
        "2.返回":0
    },
    "3.模拟":baseMod,
    "4.退出":offStatus
}




thismenu = menu(starMessager,devMenu)
starMessager.startServers()


starMessager.workModule = thismenu
starMessager.workModule.show()